<template>
  <div>
    <h1>Role Management</h1>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>Role List</span>
          <el-button type="primary" @click="showAddDialog = true" v-if="canAddRole">Add Role</el-button>
        </div>
      </template>
      <div class="card-content">
        <el-table :data="roles" style="width: 100%">
          <el-table-column prop="name" label="Role Name" width="180" />
          <el-table-column prop="description" label="Description" />
          <el-table-column label="Permissions">
            <template #default="scope">
              <el-tag v-for="perm in scope.row.permissions" :key="perm" style="margin-right: 5px">
                {{ perm }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="Operations" width="180">
            <template #default="scope">
              <el-button size="small" @click="handleEdit(scope.row)">Edit</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">Delete</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- Add Role Dialog -->
    <el-dialog v-model="showAddDialog" title="Add New Role" width="30%">
<el-form :model="newRole" :rules="rules" ref="addFormRef" label-width="100px">
  <el-form-item label="Role Name" prop="name" required>
    <el-input v-model="newRole.name" />
  </el-form-item>
  <el-form-item label="Description" prop="description">
    <el-input v-model="newRole.description" type="textarea" />
  </el-form-item>
  <el-form-item label="Permissions" prop="permissions" required>
    <el-select v-model="newRole.permissions" multiple placeholder="Select permissions">
      <el-option
        v-for="perm in allPermissions"
        :key="perm"
        :label="perm"
        :value="perm"
      />
    </el-select>
  </el-form-item>
</el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">Cancel</el-button>
        <el-button type="primary" @click="handleAdd">Confirm</el-button>
      </template>
    </el-dialog>

    <!-- Edit Role Dialog -->
    <el-dialog v-model="showEditDialog" title="Edit Role" width="30%">
<el-form :model="editingRole" :rules="editRules" ref="editFormRef" label-width="100px">
  <el-form-item label="Role Name">
    <el-input v-model="editingRole.name" disabled />
  </el-form-item>
  <el-form-item label="Description" prop="description">
    <el-input v-model="editingRole.description" type="textarea" />
  </el-form-item>
  <el-form-item label="Permissions" prop="permissions" required>
    <el-select v-model="editingRole.permissions" multiple placeholder="Select permissions">
      <el-option
        v-for="perm in allPermissions"
        :key="perm"
        :label="perm"
        :value="perm"
      />
    </el-select>
  </el-form-item>
</el-form>
      <template #footer>
        <el-button @click="showEditDialog = false">Cancel</el-button>
        <el-button type="primary" @click="handleUpdate">Save</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/api'

const roles = ref([])
const allPermissions = ref([])
const showAddDialog = ref(false)
const showEditDialog = ref(false)

const newRole = ref({
  name: '',
  description: '',
  permissions: []
})

const editingRole = ref({
  id: null,
  name: '',
  description: '',
  permissions: []
})

onMounted(async () => {
  await fetchRoles()
  await fetchPermissions()
})

const fetchRoles = async () => {
  try {
    const response = await api.role.getRoles()
    roles.value = response.data.map(role => ({
      id: role.id,
      name: role.name,
      description: role.description,
      permissions: role.permissions?.map(p => p.name) || []
    }))
  } catch (error) {
    ElMessage.error('Failed to fetch roles')
    console.error(error)
  }
}

const fetchPermissions = async () => {
  try {
    const response = await api.permission.getPermissions()
    allPermissions.value = response.data.map(p => p.name)
  } catch (error) {
    ElMessage.error('Failed to fetch permissions')
    console.error(error)
  }
}

const handleEdit = (role) => {
  editingRole.value = {
    id: role.id,
    name: role.name,
    description: role.description,
    permissions: [...role.permissions]
  }
  showEditDialog.value = true
}

const handleUpdate = async () => {
  try {
    await api.role.updateRole(editingRole.value.id, {
      id: editingRole.value.id,
      name: editingRole.value.name,
      description: editingRole.value.description,
      permissions: editingRole.value.permissions.map(p => ({name: p}))
    })
    await fetchRoles()
    showEditDialog.value = false
    ElMessage.success('Role updated successfully')
  } catch (error) {
    ElMessage.error(error.response?.data?.message || 'Failed to update role')
  }
}

const handleDelete = async (role) => {
  try {
    await ElMessageBox.confirm(
      `Delete role ${role.name}? This action cannot be undone.`,
      'Warning',
      { 
        type: 'warning',
        customClass: 'delete-confirm',
        center: true
      }
    )
    await api.role.deleteRole(role.id)
    await fetchRoles()
    ElMessage.success('Role deleted successfully')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('Failed to delete role')
    }
  }
}

const handleAdd = async () => {
  try {
    await api.role.createRole(newRole.value)
    await fetchRoles()
    showAddDialog.value = false
    newRole.value = { name: '', description: '', permissions: [] }
    ElMessage.success('Role created successfully')
  } catch (error) {
    ElMessage.error(error.response?.data?.message || 'Failed to create role')
  }
}
</script>

<style scoped>
@import '@/assets/common.css';

.box-card {
  composes: common-card;
}
.card-header {
  composes: common-card-header;
}
.card-content {
  composes: common-card-content;
}
</style>
